package com.asyf.shoporder.common;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常处理页面
 * <p>
 * sentinel-1.8版本找不到UrlBlockHandler接口，如何自定义错误页面？实现接口：BlockExceptionHandler
 */
@Component
public class ExceptionHandlerPage implements BlockExceptionHandler {

    // BlockException 异常接口,包含Sentinel的五个异常@SentinelResource用于定义资源，并提供可选的异常处理和 fallback 配置项。其主要参数如下:
    // FlowException 限流异常
    // DegradeException 降级异常
    // ParamFlowException 参数限流异常
    // AuthorityException 授权异常
    // SystemBlockException 系统负载异常
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        ResponseData data = null;
        if (e instanceof FlowException) {
            data = new ResponseData(-1, "接口被限流了...");
        } else if (e instanceof DegradeException) {
            data = new ResponseData(-2, "接口被降级了...");
        } else if (e instanceof ParamFlowException) {
            data = new ResponseData(-3, "接口被热点参数限流了...");
        } else if (e instanceof SystemBlockException) {
            data = new ResponseData(-4, "系统规则（负载/...不满足要求）...");
        } else if (e instanceof AuthorityException) {
            data = new ResponseData(-5, "授权规则不通过...");
        }
        response.getWriter().write(JSON.toJSONString(data));
    }

}
